package pit.com.ordermobilesystem.fragment;

import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pit.com.ordermobilesystem.BaseFragment;
import pit.com.ordermobilesystem.ShopActivity;
import pit.com.ordermobilesystem.R;
import pit.com.ordermobilesystem.BaseFragment.TypeLoadingMore;
import pit.com.ordermobilesystem.adapter.ItemAdapter;
import pit.com.ordermobilesystem.fragment.CategoryFragment.LoadingCategory;
import pit.com.ordermobilesystem.http.HttpApiException;
import pit.com.ordermobilesystem.http.OrderSystemHttpService;
import pit.com.ordermobilesystem.provider.OrderMobileProvider;
import pit.com.ordermobilesystem.provider.OrderMobileProvider.ItemTable;
import pit.com.ordermobilesystem.sharepreference.OrderSharePreference;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.etsy.android.grid.StaggeredGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;




public class ItemFragment extends BaseFragment {
	
	LinearLayout lay_more;
	LinearLayout lay_error;
	TextView tv_error;
	StaggeredGridView listView;
	ItemAdapter adapter;
	int category_id=0;
	SwipeRefreshLayout swipeLayout;	 
	/**
	 * Thong Nguyen Catch notification from content provider at step 8' option A
	 */
	ContentObserver contentObserver = new ContentObserver(new Handler()) {

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			synchronized (this) {
				Cursor data = getActivity().getContentResolver().query(
						OrderMobileProvider.ITEM_CONTENT_URI, null, ItemTable.ID_CATEGORY+"="+category_id, null,
						null);
				if (data != null) {
		
						if (adapter == null) {
							adapter = new ItemAdapter(getActivity(), data);
							listView.setAdapter(adapter);
						} else {

							adapter.changeCursor(data);
							
						}	

				}				

			}
		}
	};
	
	
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        name="ItemFragment";
		category_id=getArguments().getInt("category_id");
	    }

	    @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
	        View rootView = inflater.inflate(R.layout.fragment_item, container, false);

	        lay_more=(LinearLayout) rootView.findViewById(R.id.lay_more);
	        lay_error=(LinearLayout) rootView.findViewById(R.id.lay_error);
	        tv_error=(TextView) rootView.findViewById(R.id.tv_error);
	        lay_error.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					lay_error.setVisibility(View.GONE);
					
				}
			});
	        
			listView=(StaggeredGridView) rootView.findViewById(R.id.ptr_listview);
			swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
			swipeLayout.setOnRefreshListener(new OnRefreshListener() {
				
				@Override
				public void onRefresh() {
					new LoadingItem(TypeLoadingMore.PULL_TO_REFRESH).execute(""+category_id);
					
				}
			});		
			
			
			getActivity().getActionBar().setTitle(getArguments().getString("category_name"));

	        new LoadingItem(TypeLoadingMore.LOADING_FIRST).execute(""+category_id);
	        return rootView;
	    }

	@Override
	public void onPause() {
		super.onPause();
		getActivity().getContentResolver().unregisterContentObserver(contentObserver);		
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		contentObserver.onChange(true);
		getActivity().getContentResolver().registerContentObserver(OrderMobileProvider.ITEM_CONTENT_URI, true, contentObserver);

	}
	    

	
	class LoadingItem extends AsyncTask<String, Void, Void> {

		TypeLoadingMore typeLoading;
		Exception exception;
		int response_code;
		
		
		public LoadingItem(TypeLoadingMore typeLoading) {
			super();
			this.typeLoading = typeLoading;
		}
		protected void onPreExecute() {
			if(typeLoading==TypeLoadingMore.LOADING_FIRST){
				showProgressDialog(new DialogInterface.OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						LoadingItem.this.cancel(true);
						dialog.dismiss();
						swipeLayout.setRefreshing(false);
					}


				});
			}

		}

		protected Void doInBackground(final String... args) {
			OrderSystemHttpService httpService=new OrderSystemHttpService(OrderSharePreference.getHost(getActivity()),OrderSharePreference.getPort(getActivity()));
			try {
				JSONObject item=new JSONObject();
				item.put("category_id", args[0]);
				JSONObject result=httpService.requestToService(OrderSystemHttpService.URL_GET_LIST_ITEM, item.toString());
				if(result.getString("status").equals("ok")){		
					JSONArray arrayCategory=result.getJSONObject("data").getJSONArray("items");
					ContentValues[] listValues=new ContentValues[arrayCategory.length()];					
					for(int i=0;i<arrayCategory.length();i++){
						listValues[i]=OrderMobileProvider.getContentValues(getActivity(),arrayCategory.getJSONObject(i));
					}
					//Insert into database
					//getActivity().getContentResolver().delete(OrderMobileProvider.ITEM_CONTENT_URI, null, null);
					getActivity().getContentResolver().bulkInsert(OrderMobileProvider.ITEM_CONTENT_URI, listValues);				
					getActivity().getContentResolver().notifyChange(OrderMobileProvider.ITEM_CONTENT_URI, null);
				}else{
					exception=new Exception(result.getString("error"));
				}

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				exception=e;
			} catch (HttpApiException e) {
				// TODO Auto-generated catch block
				exception=e;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				exception=e;
			}
			return null;
		}

		protected void onPostExecute(final Void unused) {
			swipeLayout.setRefreshing(false);
			hideProgressDialog();
			if(exception!=null){
				showAlert("",exception.getMessage());
			}

		}

	}
		    
}
